package L612;

/**
 * @program: javase
 * @description: 二分查找
 * @author: luolidong
 * @create: 2021-06-12 19:47
 * @version: 1.0
 */
public class Demo5 {
    public int search(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        int mid = 0;
        while (l <= r) {
            mid = (l + r) / 2;
            if (nums[mid] > target) {
                r = mid - 1;
            } else if (nums[mid] < target) {
                l = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public int search1(int[] nums, int target) {
        return mid(nums, target, 0, nums.length - 1);
    }

    public int mid(int[] nums, int target, int l, int r) {
        if (l > r) return -1;
        int mid = (l + r) / 2;
        if (nums[mid] > target) {
            return mid(nums, target, l, mid - 1);
        } else if (nums[mid] < target) {
            return mid(nums, target, mid + 1, r);
        } else {
            return mid;
        }

    }

    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3, 5, 6, 7, 8, 9, 10};
        int mid = new Demo5().mid(a, 7, 0, a.length - 1);//5
        System.out.println("mid = " + mid);
    }
}
